#include "MyString.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

void Print(MyString *obj);
int IsEqual(MyString *obj1, MyString *obj2);
int IsContains(MyString *dest, MyString *src);
int Size(MyString *obj);
void RemoveString(MyString *dest, const char *str);
void InsertString(MyString *dest, const char *str, int index);

void Initiallize(MyString *obj, const char *str)
{

        obj->size = strlen(str);
        // new note
        obj->string = (char *)malloc(sizeof(char) * (obj->size + 1));
        if (obj->string == NULL)
        {
                printf("MyString malloc error!\n");
                return;
        }
        strcpy(obj->string, str);

        // func Init
        obj->print = Print;
        obj->IsContains = IsContains;
        obj->isEqual = IsEqual;
        obj->StrintSize = Size;
        obj->insertString = InsertString;
        obj->removeString = RemoveString;
}
void FreeMyString(MyString *obj)
{
        if (obj->string != NULL)
        {
                free(obj->string);
                obj->string = NULL;
        }
}
void Print(MyString *obj)
{
        printf("%s\n", obj->string);
}

int IsEqual(MyString *obj1, MyString *obj2)
{
        if (strcmp(obj1->string, obj2->string) == 0)
        {
                return 1;
        }
        else
        {
                return 0;
        }
}

int IsContains(MyString *dest, MyString *src)
{
        char *str = strstr(dest->string, src->string);
        if (str == NULL)
        {
                return 0;
        }
        else
        {
                return 1;
        }
}

int Size(MyString *obj)
{
        return obj->size;
}

void RemoveString(MyString *dest, const char *str)
{
        char *RMstr = strstr(dest->string, str);
        if (RMstr == NULL)
        {
                return;
        }
        else
        {
                char *destination = RMstr + strlen(str);
                while (*destination != '\0')
                {
                        *RMstr = *destination;
                        RMstr++;
                        destination++;
                }
                *RMstr = '\0';
        }
}

void InsertString(MyString *obj, const char *str, int index)
{
        if (index < 0 || index > obj->size)
        {
                return;
        }

        int new_str_len = obj ->size + strlen(str) + 1;
        char *new_str = (char *)malloc(new_str_len);
        if (new_str == NULL)
        {
                printf("insertString malloc error!\n");
                return;
        }

        strncpy(new_str, obj->string, index);
        strncpy(new_str + index, str, strlen(str));
        strcpy(new_str + index + strlen(str), obj->string + index);

        free(obj->string);
        obj->string = new_str;
        obj->size = strlen(obj->string);
}
